<script setup lang="ts">
import GoodsCard from './GoodsCard.vue'
import { ref, watch, defineProps, defineEmits } from 'vue'

interface GoodsItem {
    title: string
    imageUrl: string
    text?: string
    description?: string
}

const props = defineProps<{ goods: GoodsItem[] }>()
const emit = defineEmits(['update:total'])

const goodsWithCount = ref(props.goods.map(item => ({ ...item, count: 0 })))

function add(idx: number) {
    goodsWithCount.value[idx].count++
    updateTotal()
}
function subtract(idx: number) {
    if (goodsWithCount.value[idx].count > 0) {
        goodsWithCount.value[idx].count--
        updateTotal()
    }
}
function getPrice(str: string) {
    const match = str.match(/\d+(\.\d+)?/)
    return match ? parseFloat(match[0]) : 0
}
function updateTotal() {
    const total = goodsWithCount.value.reduce((sum, item) => sum + (item.count * getPrice(item.description || '0')), 0)
    emit('update:total', total)
}

watch(() => props.goods, (newGoods) => {
    goodsWithCount.value = newGoods.map(item => ({ ...item, count: 0 }))
})
</script>

<template>
    <div>
        <GoodsCard
          v-for="(item, idx) in goodsWithCount"
          :key="idx" :title="item.title"
          :image-url="item.imageUrl"
          :text="item.text"
          :description="item.description"
          :count="item.count" @add="add(idx)"
          @subtract="subtract(idx)" />
    </div>`+
</template>
